<template>
  <div class="h-screen w-full relative bg-gradient-to-br from-gray-900 via-blue-950 to-black overflow-hidden pt-20">
    <MainMenu />
    <div id="map" class="h-full w-full border-2 border-blue-800/40">
      <!-- 地图十字丝 -->
      <div class="pointer-events-none fixed inset-0 z-10 flex items-center justify-center">
        <div class="relative w-16 h-16">
          <!-- 十字丝中心点 -->
          <div class="absolute left-1/2 top-1/2 w-2 h-2 -ml-1 -mt-1 rounded-full bg-[#00eaff] shadow-[0_0_8px_rgba(0,234,255,0.6)]"></div>
          <!-- 水平线 -->
          <div class="absolute left-0 top-1/2 w-full h-px">
            <div class="w-[6px] h-px bg-[#00eaff] shadow-[0_0_8px_rgba(0,234,255,0.6)] absolute left-0"></div>
            <div class="w-[6px] h-px bg-[#00eaff] shadow-[0_0_8px_rgba(0,234,255,0.6)] absolute right-0"></div>
          </div>
          <!-- 垂直线 -->
          <div class="absolute top-0 left-1/2 h-full w-px">
            <div class="w-px h-[6px] bg-[#00eaff] shadow-[0_0_8px_rgba(0,234,255,0.6)] absolute top-0"></div>
            <div class="w-px h-[6px] bg-[#00eaff] shadow-[0_0_8px_rgba(0,234,255,0.6)] absolute bottom-0"></div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 地图工具条 -->
    <div class="fixed right-4 top-24 z-30 space-y-4">
      <MapToolbar
        :map="map"
        :toggleLayerManager="toggleLayerManager"
        :switchMapStyle="switchMapStyle"
        :toggleGlobe="toggleGlobe"
        :resetMap="resetMap"
        :toggleFullscreen="toggleFullscreen"
      />
      <DataImportToolbar :map="map" />
    </div>
    
    <!-- 地图控件 -->
    <MapControls :map="map" />
    
    <!-- 图层管理 -->
    <MapLayerManager v-if="map && showLayerManager" :map="map" />
    

    <!-- 地图中心经纬度显示 -->
    <div class="fixed right-4 bottom-6 z-20 bg-[#0a1a2f]/80 text-cyan-200 px-4 py-2 rounded-lg shadow-lg border border-cyan-400/30 text-xs font-mono select-none flex items-center space-x-2">
      <i class="fas fa-location-arrow fa-crosshairs text-cyan-300"></i>
      <span>经度: {{ currentLng.toFixed(6) }}° &nbsp; 纬度: {{ currentLat.toFixed(6) }}°</span>
    </div>
    
    <!-- 背景发光特效 -->
    <div class="pointer-events-none fixed inset-0 z-0">
      <div class="absolute left-1/3 top-1/4 w-96 h-96 bg-blue-500/20 blur-3xl rounded-full animate-pulse"></div>
      <div class="absolute right-1/4 bottom-1/4 w-80 h-80 bg-cyan-400/10 blur-2xl rounded-full animate-pulse"></div>
    </div>
  </div>
</template>

<script setup>
import { onMounted, onUnmounted, ref } from 'vue'
import maplibregl from 'maplibre-gl'
import 'maplibre-gl/dist/maplibre-gl.css'
import MainMenu from '../components/MainMenu.vue'
import MapControls from '../components/MapControls.vue'
import MapLayerManager from '../components/MapLayerManager.vue'
import MapToolbar from '../components/MapToolbar.vue'
import DataImportToolbar from '../components/DataImportToolbar.vue'

const map = ref(null)
let popup = null

// 图层面板可见性
const showLayerManager = ref(true)
function toggleLayerManager() {
  showLayerManager.value = !showLayerManager.value
}

// 地图样式切换
const mapStyles = ['/mapstyle.json', '/mapstyle-dark.json']
const currentStyleIdx = ref(0)
function switchMapStyle() {
  if (!map.value) return
  currentStyleIdx.value = (currentStyleIdx.value + 1) % mapStyles.length
  map.value.setStyle(mapStyles[currentStyleIdx.value])
}

// globe模式切换
const isGlobe = ref(false)
function toggleGlobe() {
  if (!map.value) return
  isGlobe.value = !isGlobe.value
  map.value.setProjection(isGlobe.value ? 'globe' : 'mercator')
}

// 地图复位
const initialCenter = [121.36329, 30.98109]
const initialZoom = 14
function resetMap() {
  if (!map.value) return
  map.value.flyTo({ center: initialCenter, zoom: initialZoom })
}

// 全屏
function toggleFullscreen() {
  const el = document.getElementById('map')?.parentElement
  if (!el) return
  if (!document.fullscreenElement) {
    el.requestFullscreen()
  } else {
    document.exitFullscreen()
  }
}

// 添加经纬度状态
const currentLng = ref(initialCenter[0])
const currentLat = ref(initialCenter[1])
// const scaleText = ref('500 m')

function getPopupHtml(lng, lat, feature = null, layerId = null) {
  if (feature) {
    // 取属性
    const props = feature.properties || {}
    const keys = Object.keys(props)
    let title = props.name || props.id || (keys.length > 0 ? props[keys[0]] : '要素')
    let rows = keys.map(k => `
      <div class='popup-row'>
        <span class='popup-label'>${k}:</span>
        <span class='popup-value'>${props[k]}</span>
      </div>
    `).join('')
    return `
      <div class="popup-tech">
        <div class="popup-header">
          <i class="fas fa-info-circle"></i>
          <span class="popup-title">${title}</span>
        </div>
        <div class="popup-content">
          <div class='popup-row'>
            <span class='popup-label'>图层ID</span>
            <span class='popup-value'>${layerId || feature.layer?.id || '未知'}</span>
          </div>
          ${rows}
          <div class='popup-row'>
            <span class='popup-label'>经度</span>
            <span class='popup-value'>${lng.toFixed(6)}</span>
          </div>
          <div class='popup-row'>
            <span class='popup-label'>纬度</span>
            <span class='popup-value'>${lat.toFixed(6)}</span>
          </div>
        </div>
      </div>
    `
  }
  // 无要素时，显示原有内容
  return `
    <div class="popup-tech">
      <div class="popup-header">
        <i class="fas fa-info-circle"></i>
        <span class="popup-title">无要素</span>
      </div>
      <div class="popup-content">
        <div class='popup-row'>
          <span class='popup-label'>经度</span>
          <span class='popup-value'>${lng.toFixed(6)}</span>
        </div>
        <div class='popup-row'>
          <span class='popup-label'>纬度</span>
          <span class='popup-value'>${lat.toFixed(6)}</span>
        </div>
      </div>
    </div>
  `
}

onMounted(() => {
  map.value = new maplibregl.Map({
    container: 'map',
    style: mapStyles[currentStyleIdx.value],
    center: initialCenter,
    hash: true,
    zoom: initialZoom
  })

  // 添加比例尺控件
  const scale = new maplibregl.ScaleControl({
    maxWidth: 150,
    unit: 'metric'
  })
  map.value.addControl(scale, 'bottom-left')

  map.value.on('load', () => {
    console.log('地图加载完成')
  })

  // 监听地图移动事件，更新经纬度
  map.value.on('move', () => {
    const center = map.value.getCenter()
    currentLng.value = center.lng
    currentLat.value = center.lat
    
    // 更新比例尺文本
    const zoom = map.value.getZoom()
    const scale = Math.round(map.value.getCenter().distanceTo(
      map.value.unproject([150, 0])  // 150px is maxWidth of scale control
    ))
    // scaleText.value = scale >= 1000 ? `${(scale/1000).toFixed(1)} km` : `${scale} m`
  })

  map.value.on('click', (e) => {
    if (popup) popup.remove()
    const { lng, lat } = e.lngLat
    // 查询点击点的所有可见矢量图层要素
    const features = map.value.queryRenderedFeatures(e.point)
    let feature = features && features.length > 0 ? features[0] : null
    let layerId = feature ? (feature.layer && feature.layer.id) : null
    popup = new maplibregl.Popup({
      closeButton: true,
      closeOnClick: true,
      className: 'popup-tech-outer'
    })
      .setLngLat([lng, lat])
      .setHTML(getPopupHtml(lng, lat, feature, layerId))
      .addTo(map.value)
  })
})

onUnmounted(() => {
  if (map.value) {
    map.value.remove()
  }
  if (popup) popup.remove()
})
</script>

<style>
.maplibregl-canvas {
  width: 100%;
  height: 100%;
}

/* 弹窗外层容器样式 */
.popup-tech-outer .maplibregl-popup-content {
  background: linear-gradient(135deg, #0a1a2f 80%, #1e3a5c 100%);
  border: 1px solid rgba(0, 234, 255, 0.3);
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 234, 255, 0.15);
  color: #e0f7fa;
  padding: 0;
  min-width: 300px;
  max-width: 600px;
  font-family: 'Microsoft YaHei', Arial, sans-serif;
  position: relative;
  backdrop-filter: blur(10px);
}

/* 弹窗关闭按钮样式 */
.popup-tech-outer .maplibregl-popup-close-button {
  width: 24px;
  height: 24px;
  font-size: 20px;
  color: #00eaff;
  background: rgba(0, 234, 255, 0.1);
  border-radius: 50%;
  right: 8px;
  top: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0;
  transition: all 0.2s ease;
}

.popup-tech-outer .maplibregl-popup-close-button:hover {
  background: rgba(0, 234, 255, 0.2);
  transform: scale(1.1);
}

/* 弹窗内容容器 */
.popup-tech {
  position: relative;
}

/* 弹窗头部样式 */
.popup-header {
  background: rgba(0, 234, 255, 0.1);
  padding: 12px 16px;
  border-bottom: 1px solid rgba(0, 234, 255, 0.2);
  border-radius: 12px 12px 0 0;
  display: flex;
  align-items: center;
  gap: 8px;
}

.popup-header i {
  color: #00eaff;
  font-size: 1.1rem;
}

.popup-title {
  font-size: 1.1rem;
  color: #00eaff;
  font-weight: 500;
  margin-right: 24px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 弹窗内容区域样式 */
.popup-content {
  padding: 12px 16px;
  max-height: 400px;
  overflow-y: auto;
}

.popup-content::-webkit-scrollbar {
  width: 6px;
}

.popup-content::-webkit-scrollbar-track {
  background: rgba(0, 234, 255, 0.05);
  border-radius: 3px;
}

.popup-content::-webkit-scrollbar-thumb {
  background: rgba(0, 234, 255, 0.2);
  border-radius: 3px;
}

/* 属性行样式 */
.popup-row {
  display: grid;
  grid-template-columns: 100px 1fr;
  gap: 12px;
  padding: 6px 0;
  align-items: center;
  border-bottom: 1px solid rgba(0, 234, 255, 0.1);
}

.popup-row:last-child {
  border-bottom: none;
}

.popup-label {
  color: rgba(224, 247, 250, 0.7);
  font-size: 0.9rem;
  text-align: right;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.popup-value {
  color: #e0f7fa;
  font-size: 0.9rem;
  word-break: break-all;
  padding-right: 8px;
}

/* 弹窗箭头样式 */
.popup-tech-outer .maplibregl-popup-tip {
  border-top-color: rgba(0, 234, 255, 0.3) !important;
  filter: drop-shadow(0 2px 4px rgba(0, 234, 255, 0.1));
}

/* 比例尺样式 */
.scale-container {
  position: fixed;
  left: 20px;
  bottom: 20px;
  z-index: 1;
  background: linear-gradient(135deg, #0a1a2f 80%, #1e3a5c 100%);
  border: 2px solid #00eaff;
  border-radius: 8px;
  padding: 8px 12px;
  box-shadow: 0 0 24px #00eaff33;
  color: #e0f7fa;
  font-family: 'Microsoft YaHei', Arial, sans-serif;
}

.scale-text {
  font-size: 0.9rem;
  color: #00eaff;
  text-align: center;
  margin-top: 4px;
}

/* 经纬度显示样式 */
.coordinates-container {
  position: fixed;
  right: 20px;
  bottom: 20px;
  z-index: 1;
  background: linear-gradient(135deg, #0a1a2f 80%, #1e3a5c 100%);
  border: 2px solid #00eaff;
  border-radius: 8px;
  padding: 8px 12px;
  box-shadow: 0 0 24px #00eaff33;
}

.coordinates-text {
  color: #00eaff;
  font-size: 0.9rem;
  font-family: 'Microsoft YaHei', Arial, sans-serif;
  white-space: nowrap;
}

/* 修改 MapLibre 默认比例尺样式 */
.maplibregl-ctrl-scale {
  border: 1px solid #00eaff !important;
  border-top: none !important;
  color: #00eaff !important;
  background-color: rgba(10, 26, 47, 0.8) !important;
}

/* 自定义指北针样式 */
.maplibregl-ctrl-compass {
  width: 44px !important;
  height: 44px !important;
  background: rgba(10, 26, 47, 0.8) !important;
  border: 1px solid rgba(0, 234, 255, 0.3) !important;
  border-radius: 8px !important;
  backdrop-filter: blur(8px);
  box-shadow: 0 2px 12px rgba(0, 234, 255, 0.15) !important;
}

.maplibregl-ctrl-compass-arrow {
  background-image: none !important;
  position: relative;
}

.maplibregl-ctrl-compass-arrow::before {
  content: '';
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 0;
  height: 0;
  border-left: 8px solid transparent;
  border-right: 8px solid transparent;
  border-bottom: 16px solid #00eaff;
}

.maplibregl-ctrl-compass-arrow::after {
  content: 'N';
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: #00eaff;
  font-size: 12px;
  font-weight: bold;
}

.maplibregl-ctrl-group {
  background: rgba(10, 26, 47, 0.8) !important;
  border: 1px solid rgba(0, 234, 255, 0.3) !important;
  border-radius: 8px !important;
  backdrop-filter: blur(8px);
  box-shadow: 0 2px 12px rgba(0, 234, 255, 0.15) !important;
}

.maplibregl-ctrl-group button {
  width: 44px !important;
  height: 44px !important;
  border-bottom: 1px solid rgba(0, 234, 255, 0.2) !important;
}

.maplibregl-ctrl-group button:hover {
  background-color: rgba(30, 58, 92, 0.8) !important;
}

.maplibregl-ctrl-group button:last-child {
  border-bottom: none !important;
}
</style> 